package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;

/**
 * Shows discard changes dialog, then presents a file dialog for the user to
 * select an existing document to edit.
 * 
 * @author SARJ
 */
public class OpenDocumentAction extends AbstractAction
{
	private static final long serialVersionUID = -1802600180873123565L;

	/** Create this action for the given frame */
	public OpenDocumentAction()
	{
		super("Open...");
	}

	/**
	 * Handles the File->Open press
	 */
	@Override
	public void actionPerformed(ActionEvent ae)
	{

		boolean cancel = false;
		Frame frame = Frame.getFrame();
		int opt = 0;

		if (frame.getChangesMade())
		{
			opt = frame.displaySaveDialog();
			if (opt == JOptionPane.YES_OPTION)
				frame.saveFile(Frame.DIALOG_MODE_CHECK);

			else if (opt == JOptionPane.CANCEL_OPTION)
				cancel = true;

		}
		System.out.println(ae.getSource());
		if (!cancel)
		{
			String directory = frame.getPreferences().getDefaultPath();
			JFileChooser dialog = new JFileChooser(directory);
			dialog.addChoosableFileFilter(new SVGFileFilter());
			int option = dialog.showOpenDialog(null);
			
			if (option == JFileChooser.OPEN_DIALOG)
			{

				File file = dialog.getSelectedFile();
				if (file != null)
				{
					frame.getPreferences().setCurrentFile(file.getName());
					frame.getPreferences().setDefaultPath(file.getPath());
					frame.openFile(file);

				}
			}
		}
	}
}
